package com.tedu.egarticle_2.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.tedu.egarticle_2.base.response.JsonResult;
import com.tedu.egarticle_2.base.response.StatusCode;
import com.tedu.egarticle_2.mapper.UserMapper;
import com.tedu.egarticle_2.pojo.dto.UserArticleParam;
import com.tedu.egarticle_2.pojo.dto.UserLoginParam;
import com.tedu.egarticle_2.pojo.entity.Article;
import com.tedu.egarticle_2.pojo.vo.ArticleVO;
import com.tedu.egarticle_2.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Api(tags = "用户模块")
@RestController
@Slf4j
@Validated
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("login")
    @ApiOperation(value = "登录功能")
    @ApiOperationSupport(order = 10)
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, @ApiIgnore HttpSession session) {
        log.debug("userLoginParam: " + userLoginParam);
        UserVO userVO = userMapper.selectUserByUsernameAndPassword(userLoginParam);
        if (userVO == null) {
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user", userVO);
        return JsonResult.ok(userVO);
    }

    @PostMapping("article")
    @ApiOperation(value = "发表文章功能")
    @ApiOperationSupport(order = 20)
    public JsonResult article(@Validated @RequestBody UserArticleParam userArticleParam, @ApiIgnore HttpSession session) {
        log.debug("userArticleParam: " + userArticleParam);
        Article article = new Article();
        BeanUtils.copyProperties(userArticleParam, article);
        UserVO userVO = (UserVO) session.getAttribute("user");
        article.setUserId(userVO.getId());
        log.debug("article: " + article);
        int count = userMapper.insertArticle(article);
        return count > 0 ? JsonResult.ok() : new JsonResult(StatusCode.OPERATION_FAILED);
    }

    @GetMapping("selectByArticleId")
    @ApiOperation(value = "查询指定文章功能")
    @ApiOperationSupport(order = 30)
    @ApiImplicitParam(name = "articleId", value = "文章编号ID", required = true)
    public JsonResult selectByArticleId(@Range(min = 1, max = 100, message = "文章编号ID在1-100之间") @RequestParam Long articleId) {
        log.debug("文章编号ID: " + articleId);
        ArticleVO articleVO = userMapper.selectArticleById(articleId);
        return articleVO != null ? JsonResult.ok(articleVO) : new JsonResult(StatusCode.OPERATION_FAILED);
    }
}